package com.base.library.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.base.library.R;

import static android.graphics.drawable.GradientDrawable.RECTANGLE;

/**
 * @author 谢铖志 on 2017/6/11 21:09
 * @version V1.0
 * @modificationHistory
 * @modify by user: 谢铖志 on 2017/6/11 21:09
 */

public class ShapeButton extends AppCompatButton {
    int shapeMode;
    int solidColor;
    int strokeColor;
    int strokeWidth;
    int radius;

    public ShapeButton(Context context) {
        super(context);
        initView(context, null);
    }

    public ShapeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public ShapeButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    public void initView(Context context, AttributeSet attrs) {
        if (!isInEditMode()) {
            TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.ShapeButton);
            shapeMode = typeArray.getInt(R.styleable.ShapeButton_shapeMode, 0);
            solidColor = typeArray.getColor(R.styleable.ShapeButton_solidColor, context.getResources().getColor(R.color.mainColor));
            strokeColor = typeArray.getColor(R.styleable.ShapeButton_strokeColor, context.getResources().getColor(R.color.mainColor));
            strokeWidth = typeArray.getDimensionPixelSize(R.styleable.ShapeButton_strokeWidth, 0);
            radius = typeArray.getDimensionPixelSize(R.styleable.ShapeButton_radius, 0);
            typeArray.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = getMeasuredHeight();
        if (shapeMode == 4) {
            radius = height / 2;
        }
        GradientDrawable gd = new GradientDrawable();
        gd.setColor(solidColor);
        if (shapeMode >= 4) {
            gd.setShape(RECTANGLE);
        } else {
            gd.setShape(shapeMode);
        }
        gd.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, radius, getResources().getDisplayMetrics()));
        gd.setStroke(strokeWidth, strokeColor);
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            setBackground(gd);
        } else {
            setBackgroundDrawable(gd);
        }
    }
}
